package controllers;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import models.User;

import utils.DAOUser;

/**
 * Servlet implementation class HomeController
 */
public class HomeController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public HomeController() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		String message = "";
		synchronized (session) {

			if (session.getAttribute("user") != null) {
				String user = (String) session.getAttribute("user");
				if (request.getParameter("viewUser") != null
						&& !request.getParameter("viewUser").equals("")) {
					DAOUser daoUser;
					try {
						// Refresh currentUser and session stats.
						daoUser = new DAOUser();
						String viewUser = request.getParameter("viewUser");
						User currentUser = daoUser.getUser(viewUser);
						daoUser.setAcceptedContact(currentUser, user);
						daoUser.setContact(currentUser, user);
						daoUser.setFollower(currentUser, user);
						session.setAttribute("numTweets", 5);
						session.setAttribute("numUsers", 5);
						if (!currentUser.getUser().equals(
								((User) session.getAttribute("currentUser"))
										.getUser()))
							session.setAttribute("contentView",
									"TweetController");

						session.setAttribute("currentUser", currentUser);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						message += "Ha habido un error al recuperar el usuario de la base de datos";
					}
				}

				request.setAttribute("message", message);

				RequestDispatcher dispatcher = request
						.getRequestDispatcher("/home.jsp");
				if (dispatcher != null)
					dispatcher.forward(request, response);
			} else {
				RequestDispatcher dispatcher = request
						.getRequestDispatcher("/index.jsp");
				if (dispatcher != null)
					dispatcher.forward(request, response);
			}
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
